<template>
  <div class="h-full overflow-auto bg-[#252526] text-[#CCCCCC]">
    <!-- 添加调试信息 -->
    <div class="p-2 text-xs text-gray-500">
      {{ fileSystemStore.files.length }} files loaded
    </div>

    <div v-for="file in sortedFiles" :key="file.path">
      <div
        @click="handleFileClick(file)"
        class="flex items-center px-4 py-1.5 hover:bg-[#2A2D2E] cursor-pointer group"
      >
        <!-- 折叠箭头 -->
        <div 
          v-if="file.type === 'directory'"
          @click.stop="toggleFolder(file)"
          class="w-4 h-4 flex items-center justify-center -ml-1"
        >
          <svg
            class="w-3 h-3 text-[#C5C5C5] transform transition-transform"
            :class="{ 'rotate-90': !isCollapsed(file) }"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
          >
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
          </svg>
        </div>

        <!-- 文件/文件夹图标 -->
        <svg 
          v-if="file.type === 'directory'" 
          class="w-4 h-4 ml-1 text-[#C5C5C5]" 
          viewBox="0 0 24 24" 
          fill="currentColor"
        >
          <path d="M20 6h-8l-2-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2z"/>
        </svg>
        
        <svg 
          v-else 
          class="w-4 h-4 ml-1" 
          :class="getFileIconColor(file.name)" 
          viewBox="0 0 24 24" 
          fill="currentColor"
        >
          <path d="M13 9V3.5L18.5 9M6 2c-1.11 0-2 .89-2 2v16c0 1.11.89 2 2 2h12c1.11 0 2-.89 2-2V8l-6-6H6z"/>
        </svg>

        <span class="text-sm ml-1">{{ file.name }}</span>
      </div>

      <!-- 子文件/文件夹 -->
      <div 
        v-if="file.children && !isCollapsed(file)" 
        class="ml-4"
      >
        <FileTree 
          :files="file.children"
          @file-click="$emit('file-click', $event)"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useFileSystemStore } from '@/stores/fileSystem'
import { readDir } from '@tauri-apps/plugin-fs'

const props = defineProps({
  directoryPath: {
    type: String,
    required: true
  }
})

const fileSystemStore = useFileSystemStore()
const files = ref([])
const collapsedFolders = ref(new Set())

watch(() => props.directoryPath, async (newPath) => {
  if (newPath) {
    try {
      const entries = await readDir(newPath, { recursive: true })
      files.value = processEntries(entries)
    } catch (error) {
      console.error('Failed to read directory:', error)
      files.value = []
    }
  }
}, { immediate: true })

// 处理文件条目
function processEntries(entries) {
  return entries.map(entry => ({
    name: entry.name,
    path: entry.path,
    type: entry.children ? 'directory' : 'file',
    children: entry.children ? processEntries(entry.children) : undefined
  }))
}

// 排序文件
const sortedFiles = computed(() => {
  console.log('Computing sorted files from:', files.value)
  return [...files.value].sort((a, b) => {
    // 文件夹在前
    if (a.type !== b.type) {
      return a.type === 'directory' ? -1 : 1
    }
    // 按名称排序
    return a.name.localeCompare(b.name)
  })
})

const isCollapsed = (file) => collapsedFolders.value.has(file.path)

const toggleFolder = (file) => {
  if (collapsedFolders.value.has(file.path)) {
    collapsedFolders.value.delete(file.path)
  } else {
    collapsedFolders.value.add(file.path)
  }
}

const handleFileClick = (file) => {
  if (file.type === 'directory') {
    toggleFolder(file)
  } else {
    console.log('Clicked file:', file.path)
  }
}

const getFileIconColor = (filename) => {
  const ext = filename.split('.').pop()?.toLowerCase()
  const colorMap = {
    js: 'text-[#FFCA28]',
    jsx: 'text-[#61DAFB]',
    ts: 'text-[#3178C6]',
    tsx: 'text-[#61DAFB]',
    vue: 'text-[#42B883]',
    css: 'text-[#42A5F5]',
    scss: 'text-[#FF69B4]',
    html: 'text-[#E44D26]',
    json: 'text-[#FBC02D]',
    md: 'text-[#42A5F5]',
    default: 'text-[#8E8E8E]'
  }
  return colorMap[ext] || colorMap.default
}
</script>

<style scoped>
.file-item:hover > .file-item {
  opacity: 0.7;
}

.scrollbar-ide::-webkit-scrollbar {
  width: 8px;
}

.scrollbar-ide::-webkit-scrollbar-track {
  background: transparent;
}

.scrollbar-ide::-webkit-scrollbar-thumb {
  background: #424242;
  border-radius: 4px;
}

.scrollbar-ide::-webkit-scrollbar-thumb:hover {
  background: #4F4F4F;
}
</style>